/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.manager;

import br.com.foxline.clinicplus.entity.*;
import br.com.foxline.clinicplus.enums.GroupProcedure;
import br.com.foxline.clinicplus.enums.PaymentType;
import br.com.foxline.clinicplus.enums.TypeDebt;
import br.com.foxline.clinicplus.enums.TypeIncome;
import br.com.foxline.clinicplus.enums.TypeProcedure;
import br.com.foxline.clinicplus.service.*;
import br.com.foxline.clinicplus.util.Msg;
import br.com.foxline.clinicplus.vo.DoctorConvenioIncome;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.model.DualListModel;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerFinancial implements Serializable {

    @EJB
    IncomeService incomeService;
    @EJB
    DoctorService doctorService;
    @EJB
    ProcedureService procedureService;
    @EJB
    SystemUserService systemUserService;
    @EJB
    OperatorService operatorService;
    @EJB
    CashService cashService;
    //POR PROCEDIMENTO
    private Procedure procedure;
    private String nameProcedure;
    private List<Procedure> procedures;
    //POR MÉDICO
    private Doctor doctor;
    private Doctor doctorSelected;
    private String nameDoctor;
    private List<Doctor> doctors;
    private DualListModel<Procedure> listModel;
    //POR USER
    private SystemUser systemUser;
    private List<SystemUser> systemUsers;
    private List<Income> incomesAll;
    private List<Income> incomes;
    private List<Income> incomesOutput;
    private BigDecimal totalOutput;
    //TOTAL PAGO
    private BigDecimal total;
    private BigDecimal totalOutputAll;
    //TOTAL GERAL
    private BigDecimal amountTotal;
    private Date dateInitial;
    private Date dateFinal;
    private boolean isDoctor;
    //POR CONVÊNIO
    private DualListModel<Operator> listOperators;
    private List<Operator> operators;
    private Operator operatorSelect;
    private Operator operator;
    private PaymentType paymentType;
    private TypeProcedure typeProcedure;
    private int relatorioconvenio;
    private GroupProcedure groupProcedure;
    //HONORARIOS
    private BigDecimal desconto;
    private Boolean debitoHonorarios;
    private BigDecimal valorDebitoHonorarios;
    //CONVENIO DOUTOR
    private List<DoctorConvenioIncome> doctorConvenioIncomes;
    private DoctorConvenioIncome doctorConvenioIncome;
    //COMPENSACAO
    private List<Income> incomesACompensar;
    private Date dataCompensacao;
    private BigDecimal totalAmountPending;
    private ContaBancaria contaBancaria;
    /**
     * Campo como filtro na tela de compensacao;
     */
    private Boolean compensado;
    private BigDecimal bruto;
    /**
     * Usado em compensacao para alterar o valor do atendimento
     */
    private BigDecimal newValueAmountPaid;
    private BigDecimal newValueAmountTotal;
    private Date dataIncome;
    private int idIncomeAlter;

    @PostConstruct
    public void init() {
        isDoctor = false;
        doctor = new Doctor();
        procedure = new Procedure();
        systemUser = new SystemUser();

        operators = operatorService.findAll();

        listOperators = new DualListModel<Operator>(operators, new ArrayList<Operator>());

        List<Procedure> source = procedureService.findAll();
        List<Procedure> target = new ArrayList<Procedure>();

        listModel = new DualListModel<Procedure>(source, target);

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        if (params.get("r") != null) {
            try {
                relatorioconvenio = Integer.parseInt(params.get("r"));
            } catch (Exception e) {
                Msg.messagemWarn("Erro");
            }
        }
        if (params.get("d") != null && !params.get("d").isEmpty()) {
            try {
                doctor = doctorService.find(Long.parseLong(params.get("d")));
                isDoctor = true;
                getInitial();
            } catch (Exception e) {
                Msg.messagemWarn("Médico não encontrado !");
            }
        }

        initDoctorConvenioIncome();
    }

    private void getInitial() {

        Calendar gc = GregorianCalendar.getInstance();
        gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        gc.set(GregorianCalendar.MILLISECOND, 0);

        dateInitial = gc.getTime();
        Calendar gc1 = GregorianCalendar.getInstance();
        gc1.set(GregorianCalendar.HOUR_OF_DAY, 23);
        gc1.set(GregorianCalendar.MINUTE, 0);
        gc1.set(GregorianCalendar.SECOND, 0);
        gc1.set(GregorianCalendar.MILLISECOND, 0);

        dateFinal = gc1.getTime();

    }

    public SystemUser getSystemUser() {
        return systemUser;
    }

    public void setSystemUser(SystemUser systemUser) {
        this.systemUser = systemUser;
    }

    public Date getDateFinal() {
        return dateFinal;
    }

    public void setDateFinal(Date dateFinal) {
        this.dateFinal = dateFinal;
    }

    public Date getDateInitial() {
        return dateInitial;
    }

    public void setDateInitial(Date dateInitial) {
        this.dateInitial = dateInitial;
    }

    public String getNameDoctor() {
        return nameDoctor;
    }

    public void setNameDoctor(String nameDoctor) {
        this.nameDoctor = nameDoctor;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public List<Doctor> getDoctors() {
        return doctors;
    }

    public void setDoctors(List<Doctor> doctors) {
        this.doctors = doctors;
    }

    public List<Income> getIncomes() {
        return incomes;
    }

    public void setIncomes(List<Income> incomes) {
        this.incomes = incomes;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }

    public String getNameProcedure() {
        return nameProcedure;
    }

    public void setNameProcedure(String nameProcedure) {
        this.nameProcedure = nameProcedure;
    }

    public Procedure getProcedure() {
        return procedure;
    }

    public void setProcedure(Procedure procedure) {
        this.procedure = procedure;
    }

    public List<Procedure> getProcedures() {
        return procedures;
    }

    public DualListModel<Procedure> getListModel() {
        return listModel;
    }

    public void setListModel(DualListModel<Procedure> listModel) {
        this.listModel = listModel;
    }

    public void setProcedures(List<Procedure> procedures) {
        this.procedures = procedures;
    }

    public void clearDoctor() {
        doctorSelected = null;
        doctor = null;
    }

    public void clearProcedure() {
        procedure = null;
    }

    public void listDoctor() {
        Doctor d = new Doctor();
        d.setName(nameDoctor);
        doctors = doctorService.findDoctor(d);
    }

    public void listProcedure() {
        Procedure p = new Procedure();
        p.setName(nameProcedure);
        procedures = procedureService.findProcedure(p, true);
    }

    public List<SystemUser> listUser(String str) {
        SystemUser su = new SystemUser();
        su.setName(str);
        return systemUserService.findUsersAtendente(su);
    }

    public void search() {
        total = incomeService.getValueIncomeGeneric(null, null, doctor, dateInitial, dateFinal, paymentType, null, TypeIncome.C, null, listModel.getTarget(), null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, null);
        incomes = incomeService.findIncomeGeneric(null, null, doctor, dateInitial, dateFinal, paymentType, null, TypeIncome.C, null, listModel.getTarget(), null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, null);
    }

    public void searchByProcedure() {
        total = incomeService.getValueIncomeGeneric(null, procedure, null, dateInitial, dateFinal, null, null, null, null, null, null, null, null, null, null, null, null);
        incomes = incomeService.findIncomeGeneric(null, procedure, null, dateInitial, dateFinal, null, null, null, null, null, null, null, null, null, null, null, null);
    }

    public void searchByUser() {
        incomesAll = incomeService.findIncomeGeneric(null, null, null, dateInitial, dateFinal, paymentType, systemUser, null, null, null, null, listOperators.getTarget(), null, null, null, null, null);

        total = incomeService.getValueIncomeGeneric(null, null, null, dateInitial, dateFinal, paymentType, systemUser, TypeIncome.C, null, null, null, listOperators.getTarget(), null, null, null, null, null);
        incomes = incomeService.findIncomeGeneric(null, null, null, dateInitial, dateFinal, paymentType, systemUser, TypeIncome.C, null, null, null, listOperators.getTarget(), null, null, null, null, null);

        incomesOutput = incomeService.findIncomeGeneric(null, null, null, dateInitial, dateFinal, null, systemUser, TypeIncome.D, null, null, null, null, null, null, null, null, null);

        if (incomesOutput != null) {
            totalOutput = BigDecimal.ZERO;

            for (Income income : incomesOutput) {
                if (income.getTotalAmount() != null) {
                    totalOutput = totalOutput.add(income.getTotalAmount());
                }
            }
        }

        System.err.println(incomesOutput);
    }

    public void searchByDate() {
        total = incomeService.getValueIncomeGeneric(null, null, null, dateInitial, dateFinal, null, null, null, null, null, null, null, null, null, null, null, null);
        incomes = incomeService.findIncomeGeneric(null, null, null, dateInitial, dateFinal, null, null, null, null, null, null, null, null, null, null, null, null);
    }

    public void searchByDateOperator() {
        total = incomeService.getValueIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, null, true, null);
        incomes = incomeService.findIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, null, null);
    }

    public void searchByCompensacao() {
        //total = incomeService.getValueIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, true);
        //amountTotal = incomeService.getValueIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, false);
        System.err.println("PESQUISANDO..");
        incomes = incomeService.findIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, null);

        total = BigDecimal.ZERO;
        amountTotal = BigDecimal.ZERO;
        totalAmountPending = BigDecimal.ZERO;

        System.err.println("LOAD..");
        for (Income income : incomes) {

            if (income.isCompensado() && income.getAmountPaid() != null) {
                total = total.add(income.getAmountPaid());
            } else {
                if (totalAmountPending != null && income.getTotalAmount() != null) {
                    totalAmountPending = totalAmountPending.add(income.getTotalAmount());
                }
            }

            if (income.isCompensado() && income.getTotalAmount() != null) {
                amountTotal = amountTotal.add(income.getTotalAmount());
            }
        }
        System.err.println("OK..");
    }

    public void initDoctorConvenioIncome() {
        doctorConvenioIncome = new DoctorConvenioIncome();
        doctorConvenioIncome.setClinica(BigDecimal.ZERO);
        doctorConvenioIncome.setCsll(BigDecimal.ZERO);
        doctorConvenioIncome.setPis(BigDecimal.ZERO);
        doctorConvenioIncome.setConfins(BigDecimal.ZERO);
        doctorConvenioIncome.setIrpj(BigDecimal.ZERO);
        doctorConvenioIncome.setIss(BigDecimal.ZERO);
        doctorConvenioIncome.setTotalDesconto(BigDecimal.ZERO);
    }

    /**
     * Prestação de conta convênio e vários medicos
     */
    public void convenioDoutor() {
        this.bruto = BigDecimal.ZERO;
        total = incomeService.getValueIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, true, null);

        doctorConvenioIncomes = new ArrayList<DoctorConvenioIncome>();
        initDoctorConvenioIncome();

        List<Doctor> d = new ArrayList<Doctor>();

        d = incomeService.findIncomeDoctor(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado);
        for (Doctor doctor : d) {
            BigDecimal bruto = (incomeService.getValueBrutoIncomeGeneric(null, null, doctor, dateInitial, dateFinal, null, null, TypeIncome.C,
                    null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado));

            doctorConvenioIncomes.add(
                    new DoctorConvenioIncome(doctor,
                    incomeService.findIncomeGenericCompensacao(null, null, doctor, dateInitial, dateFinal, null, null,
                    TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, null),
                    bruto));

            this.bruto = this.bruto.add(bruto);
        }

    }

    /**
     * Prestação de conta de um medico
     */
    public void prestacaoHonorario() {
        total = incomeService.getValueIncomeGenericCompensacao(null, null, null, dateInitial, dateFinal, null, null, TypeIncome.C, null, null, null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, true, null);

        doctorConvenioIncomes = new ArrayList<DoctorConvenioIncome>();
        initDoctorConvenioIncome();

        doctorConvenioIncomes.add(
                new DoctorConvenioIncome(doctor,
                incomeService.findIncomeGenericCompensacao(null, null, doctor, dateInitial, dateFinal, paymentType, null, TypeIncome.C, null, listModel.getTarget(), null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, dataCompensacao),
                incomeService.getValueIncomeGenericCompensacao(null, null, doctor, dateInitial, dateFinal, paymentType, null, TypeIncome.C, null, listModel.getTarget(), null, listOperators.getTarget(), null, typeProcedure, groupProcedure, compensado, true, dataCompensacao)));

    }

    public void compensarPagamentoConvenio() {

        //SALVANDO O CASH E SETANDO NO INCOME
        Cash cash = new Cash();
        if (contaBancaria != null && contaBancaria.getId() != null) {
            BigDecimal valor = BigDecimal.ZERO;
            cash.setContaBancaria(contaBancaria);
            cash.setCreatAt(new Date());
            cash.setTypeIncome(TypeIncome.C);
            String desc = "Compensacao do convênio ";
            for (Operator o : listOperators.getTarget()) {
                o = operatorService.find(o.getId());
                desc += "" + o.getName() + ", ";
            }
            if (dateInitial != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                desc += sdf.format(dateInitial);
                if (dateFinal != null) {
                    desc += " - " + sdf.format(dateFinal);
                }
            }

            cash.setDescription(desc);
            cash.setSystemUser(systemUserService.getCurrentUser());

            for (Income income : incomesACompensar) {
                if (!income.isCompensado()) {
                    if(income.getAmountPaid() == null || income.getAmountPaid().compareTo(BigDecimal.ZERO) == 0){
                        valor = valor.add(income.getTotalAmount());
                    }else{
                        valor = valor.add(income.getAmountPaid());
                    }
                }
            }
            cash.setValue(valor);
            cashService.save(cash);
        } else {
            Msg.messagemError("Conta Bancária é obrigatória");
            return;
        }


        for (Income income : incomesACompensar) {
            try {
                if (!income.isCompensado()) {
                    
                    if(income.getAmountPaid() == null || income.getAmountPaid().compareTo(BigDecimal.ZERO) == 0){
                        income.setAmountPaid(income.getTotalAmount());
                    }
                    
                    income.setCompensado(true);
                    //ATRIBUI CASH
                    income.setCash(cash);
                    if (dataCompensacao != null) {
                        income.setDataCompensacao(dataCompensacao);
                    } else {
                        income.setDataCompensacao(new Date());
                    }
                    income.setResponsavelCompensacao(systemUserService.getCurrentUser());
                    incomeService.update(income);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Msg.messagemError("Falha ao compensar registro do paciente " + income.getDiary().getCustomer().getName());
            }
        }
        Msg.messagemInfo();
    }

    public void calcularDescontos() {
        if (doctorConvenioIncomes != null) {
            valorDebitoHonorarios = BigDecimal.ZERO;
            for (DoctorConvenioIncome dci : doctorConvenioIncomes) {
                dci.setClinica(doctorConvenioIncome.getClinica());
                dci.setCsll(doctorConvenioIncome.getCsll());
                dci.setPis(doctorConvenioIncome.getPis());
                dci.setConfins(doctorConvenioIncome.getConfins());
                dci.setIrpj(doctorConvenioIncome.getIrpj());
                dci.setIss(doctorConvenioIncome.getIss());

                dci.setTotalDesconto(dci.getClinica().add(dci.getCsll()).add(dci.getPis()).add(dci.getConfins()).add(dci.getIrpj()).add(dci.getIss()));

                dci.setValorLiquido(dci.getValorBruto().subtract(dci.getValorBruto().multiply(dci.getTotalDesconto())));
                if (debitoHonorarios != null && debitoHonorarios) {
                    valorDebitoHonorarios = valorDebitoHonorarios.add(dci.getValorLiquido());
                }
            }
        }
    }

    public void loadValor(int id) {
        idIncomeAlter = id;
        Income i = incomes.get(id);
        newValueAmountPaid = i.getAmountPaid();
        newValueAmountTotal = i.getTotalAmount();
        dataIncome = i.getCreateAt();
    }

    public void alterarValor() {
        try {
            System.err.println("ALTERADO");
            Income i = incomes.get(idIncomeAlter);
            i = incomeService.find(i.getId());
            i.setAmountPaid(newValueAmountPaid);
            i.setTotalAmount(newValueAmountTotal);
            i.setAmount(newValueAmountTotal);
            i.setCreateAt(dataIncome);
            i.setSystemUser(systemUserService.getCurrentUser());
            incomeService.update(i);
            i = incomeService.find(i.getId());
            incomes.set(idIncomeAlter, i);
            Msg.messagemInfo("Valores atualizados com sucesso!");
        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError();
        }
    }

    public void cancelarCompensacao(int id) {
        try {
            Income i = incomes.get(id);
            i = incomeService.find(i.getId());

            if (i != null) {

                //DEBITANDO O VALOR DA COMPENSCAO CANCELADA 
                Cash cash = new Cash();
                if (i.getCash() != null) {
                    cash.setContaBancaria(i.getCash().getContaBancaria());
                    cash.setCreatAt(new Date());
                    cash.setTypeIncome(TypeIncome.D);
                    String desc = "Cancelamento de compensação código " + i.getId();
                    cash.setDescription(desc);
                    cash.setSystemUser(systemUserService.getCurrentUser());
                    cash.setValue(i.getAmountPaid().multiply(new BigDecimal("-1")));
                    cashService.save(cash);
                }

                i.setCash(null);
                i.setCompensado(false);
                i.setDataCompensacao(null);
                i.setResponsavelCompensacao(null);

                incomeService.update(i);
                Msg.messagemInfo("Cancelamento de compensação realizado com sucesso!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError();
        }
    }

    public boolean isIsDoctor() {
        return isDoctor;
    }

    public void setIsDoctor(boolean isDoctor) {
        this.isDoctor = isDoctor;
    }

    public void selectOperator() {
        operator = operatorSelect;
    }

    public Operator getOperator() {
        return operator;
    }

    public void setOperator(Operator operator) {
        this.operator = operator;
    }

    public Operator getOperatorSelect() {
        return operatorSelect;
    }

    public void setOperatorSelect(Operator operatorSelect) {
        this.operatorSelect = operatorSelect;
    }

    public List<Operator> getOperators() {
        return operators;
    }

    public void setOperators(List<Operator> operators) {
        this.operators = operators;
    }

    public List<SystemUser> getSystemUsers() {
        return systemUsers;
    }

    public void setSystemUsers(List<SystemUser> systemUsers) {
        this.systemUsers = systemUsers;
    }

    public void clearOperator() {
        operator = null;
    }

    public PaymentType getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(PaymentType paymentType) {
        this.paymentType = paymentType;
    }

    public List<SelectItem> selectPaymentType() {
        List<SelectItem> paymentTypes = new ArrayList<SelectItem>();
        for (PaymentType ms : PaymentType.values()) {
            paymentTypes.add(new SelectItem(ms, ms.getName()));
        }
        return paymentTypes;
    }

    public List<SelectItem> selectTypeProcedure() {
        List<SelectItem> typeProcedures = new ArrayList<SelectItem>();
        for (TypeProcedure ms : TypeProcedure.values()) {
            typeProcedures.add(new SelectItem(ms, ms.getName()));
        }
        return typeProcedures;
    }

    public List<SelectItem> selectGroupProcedure() {
        List<SelectItem> list = new ArrayList<SelectItem>();

        for (GroupProcedure ms : GroupProcedure.values()) {
            list.add(new SelectItem(ms, ms.getName()));
        }
        return list;
    }

    public Doctor getDoctorSelected() {
        return doctorSelected;
    }

    public void setDoctorSelected(Doctor doctorSelected) {
        this.doctorSelected = doctorSelected;
    }

    public void selectDoctor() {
        doctor = doctorSelected;
    }

    public DualListModel<Operator> getListOperators() {
        return listOperators;
    }

    public void setListOperators(DualListModel<Operator> listOperators) {
        this.listOperators = listOperators;
    }

    public void report() {
        if (relatorioconvenio != 1) {
            incomeService.reportIncome(incomes);
        } else {
            incomeService.reportIncomePrestacaoConta(incomes);
        }
    }

    public void reportAll() {
        incomeService.reportIncomeAll(incomes, "Relatório");
    }

    public void reportUser() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        String titulo = "Relatório - " + (systemUser != null ? systemUser.getName() : "") + " - "
                + (dateInitial != null ? sdf.format(dateInitial) + " até " : "") + ""
                + (dateFinal != null ? sdf.format(dateFinal) : "");

        if (totalOutput != null && totalOutput.compareTo(BigDecimal.ZERO) >= 0) {
            totalOutput = totalOutput.multiply(new BigDecimal("-1"));
        }
        incomeService.reportCaixaResumo(incomesAll, titulo, total, totalOutput);
    }

    public void reportFeesAll() {
        incomeService.reportIncomeAll(incomes, "Relatório", desconto);
    }

    public void reportPrestacaoConvenio() {
        calcularDescontos();
        String titulo = " ";
        for (Operator operator1 : listOperators.getTarget()) {
            operator1 = operatorService.find(operator1.getId());
            titulo += operator1.getName() + ", ";
        }

        registrarSaidaHonorarios(titulo);
        incomeService.reportIncomePrestacaoContaDoctor(doctorConvenioIncomes, "Relatório - " + titulo);
    }

    public void registrarSaidaHonorarios(String operators) {
        if (debitoHonorarios != null && debitoHonorarios) {
            if (contaBancaria == null) {
                System.err.println("cb");
                Msg.messagemError("Conta Bancária é obrigatória");
                return;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Income income = new Income();
            valorDebitoHonorarios = valorDebitoHonorarios.divide(BigDecimal.ONE, 2, RoundingMode.CEILING);
            income.setTypeIncome(TypeIncome.D);
            income.setTypeDebt(TypeDebt.HONORARIOS);
            income.setTotalAmount(valorDebitoHonorarios);
            income.setAmount(valorDebitoHonorarios);
            income.setAmountPaid(valorDebitoHonorarios);
            income.setAmountCard(BigDecimal.ZERO);
            income.setAmountMoney(BigDecimal.ZERO);
            income.setDiscount(BigDecimal.ZERO);
            income.setSystemUser(systemUserService.getCurrentUser());
            income.setDescricao("Honorários Dr. " + doctor.getName() + " referente ao(s) Convênio(s) " + operators
                    + " no período de " + sdf.format(dateInitial) + " - " + sdf.format(dateFinal));

            Calendar gc1 = GregorianCalendar.getInstance();
            gc1.set(GregorianCalendar.HOUR_OF_DAY, 12);
            income.setCreateAt(gc1.getTime());

            //SALVANDO NO CASH
            Cash cash = new Cash();
            cash.setValue(income.getTotalAmount().multiply(new BigDecimal("-1")));
            cash.setCreatAt(new Date());
            cash.setSystemUser(systemUserService.getCurrentUser());
            cash.setTypeIncome(TypeIncome.D);
            cash.setDescription(income.getTypeDebt().getDesc() + " - " + income.getDescricao());
            cash.setContaBancaria(contaBancaria);
            cashService.save(cash);

            income.setCash(cash);

            System.err.println(income);
            incomeService.save(income);
            income = new Income();
            Msg.messagemInfo("Débito de Honorários realizado com sucesso");
        }
    }

    public int getRelatorioconvenio() {
        return relatorioconvenio;
    }

    public void setRelatorioconvenio(int relatorioconvenio) {
        this.relatorioconvenio = relatorioconvenio;
    }

    public TypeProcedure getTypeProcedure() {
        return typeProcedure;
    }

    public void setTypeProcedure(TypeProcedure typeProcedure) {
        this.typeProcedure = typeProcedure;
    }

    public GroupProcedure getGroupProcedure() {
        return groupProcedure;
    }

    public void setGroupProcedure(GroupProcedure groupProcedure) {
        this.groupProcedure = groupProcedure;
    }

    public BigDecimal getDesconto() {
        return desconto;
    }

    public void setDesconto(BigDecimal desconto) {
        this.desconto = desconto;
    }

    public List<DoctorConvenioIncome> getDoctorConvenioIncomes() {
        return doctorConvenioIncomes;
    }

    public void setDoctorConvenioIncomes(List<DoctorConvenioIncome> doctorConvenioIncomes) {
        this.doctorConvenioIncomes = doctorConvenioIncomes;
    }

    public DoctorConvenioIncome getDoctorConvenioIncome() {
        return doctorConvenioIncome;
    }

    public void setDoctorConvenioIncome(DoctorConvenioIncome doctorConvenioIncome) {
        this.doctorConvenioIncome = doctorConvenioIncome;
    }

    public List<Income> getIncomesACompensar() {
        return incomesACompensar;
    }

    public void setIncomesACompensar(List<Income> incomesACompensar) {
        this.incomesACompensar = incomesACompensar;
    }

    public Boolean getCompensado() {
        return compensado;
    }

    public void setCompensado(Boolean compensado) {
        this.compensado = compensado;
    }

    public BigDecimal getBruto() {
        return bruto;
    }

    public void setBruto(BigDecimal bruto) {
        this.bruto = bruto;
    }

    public Date getDataCompensacao() {
        return dataCompensacao;
    }

    public void setDataCompensacao(Date dataCompensacao) {
        this.dataCompensacao = dataCompensacao;
    }

    public Boolean getDebitoHonorarios() {
        return debitoHonorarios;
    }

    public void setDebitoHonorarios(Boolean debitoHonorarios) {
        this.debitoHonorarios = debitoHonorarios;
    }

    public BigDecimal getAmountTotal() {
        return amountTotal;
    }

    public void setAmountTotal(BigDecimal amountTotal) {
        this.amountTotal = amountTotal;
    }

    public BigDecimal getTotalAmountPending() {
        return totalAmountPending;
    }

    public void setTotalAmountPending(BigDecimal totalAmountPending) {
        this.totalAmountPending = totalAmountPending;
    }

    public BigDecimal getNewValueAmountPaid() {
        return newValueAmountPaid;
    }

    public void setNewValueAmountPaid(BigDecimal newValueAmountPaid) {
        this.newValueAmountPaid = newValueAmountPaid;
    }

    public BigDecimal getNewValueAmountTotal() {
        return newValueAmountTotal;
    }

    public void setNewValueAmountTotal(BigDecimal newValueAmountTotal) {
        this.newValueAmountTotal = newValueAmountTotal;
    }

    public Date getDataIncome() {
        return dataIncome;
    }

    public void setDataIncome(Date dataIncome) {
        this.dataIncome = dataIncome;
    }

    public ContaBancaria getContaBancaria() {
        return contaBancaria;
    }

    public void setContaBancaria(ContaBancaria contaBancaria) {
        this.contaBancaria = contaBancaria;
    }

    public List<Income> getIncomesOutput() {
        return incomesOutput;
    }

    public void setIncomesOutput(List<Income> incomesOutput) {
        this.incomesOutput = incomesOutput;
    }

    public BigDecimal getTotalOutput() {
        return totalOutput;
    }

    public void setTotalOutput(BigDecimal totalOutput) {
        this.totalOutput = totalOutput;
    }
}
